<?php

namespace App\Services\Admin\ActionLog;

use App\Events\AdminLog\Log;
use App\Http\Controllers\Common\OperationLogController as LogController;

class ActionLog
{
    private $adminLog;

    public function __construct()
    {
        $this->adminLog = new LogController();
    }

    /**
     * 查询log日志
     * @param $sign     操作标记
     * @param $error    操作失败或成功  0  失败
     */
    public function addAdminLog($sign, $error, $code, $message)
    {
        //判断是否写日志
        $mark = $this->adminLog->enable();

        if ($mark) {
            //判断是否为文件上传
            if (isset(request()->all()['file'])) {
                $upload = request()->file('file');
                $params = \GuzzleHttp\json_encode(['fileName', $upload->getClientOriginalName()]);
            } else {
                $params = \GuzzleHttp\json_encode(request()->all());
            }

            //操作失败
            if ($error == 0) {
                if (strlen($sign) > 0) {
                    event(new Log([$code, $sign . '操作失败'], $this->getUserId(), $params));
                    return;
                }
            }

            //为登录及其用户不存在   暂时不做记录
            /* if($error == 3){
                 $data = $this->model->getOperationPermission($sign);
                 event(new Log($data['title'] . '失败', $params, $this->distinct($data['title'])));
                 return;
             }*/

            event(new Log([$code, $sign], $this->getUserId(), $params));
        }
    }

    /**
     * 储存日志
     */
    public function storeLogOverdue()
    {

    }

    /**
     * 获取用户id
     */
    protected function getUserId()
    {
        $user = request()->user();

        if (!$user) {
            return null;
        }

        return $user->id;
    }
}